using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using GenerativeAgents.Core;

namespace GenerativeAgents.Unity.UI
{
    /// <summary>
    /// 智能体监控UI
    /// 提供智能体状态监控、调试和控制功能
    /// </summary>
    public class AgentMonitorUI : MonoBehaviour
    {
        [Header("UI组件引用")]
        [SerializeField] private Canvas mainCanvas;
        [SerializeField] private GameObject agentListPanel;
        [SerializeField] private GameObject detailPanel;
        [SerializeField] private GameObject controlPanel;
        
        [Header("智能体列表UI")]
        [SerializeField] private Transform agentListContent;
        [SerializeField] private GameObject agentItemPrefab;
        [SerializeField] private ScrollRect agentListScrollRect;
        
        [Header("详细信息UI")]
        [SerializeField] private Text agentNameText;
        [SerializeField] private Text agentStateText;
        [SerializeField] private Text memoryCountText;
        [SerializeField] private Text currentActionText;
        [SerializeField] private Text locationText;
        [SerializeField] private Text moodText;
        [SerializeField] private Text energyText;
        [SerializeField] private ScrollRect memoryScrollRect;
        [SerializeField] private Transform memoryContent;
        [SerializeField] private GameObject memoryItemPrefab;
        
        [Header("控制面板UI")]
        [SerializeField] private Button pauseButton;
        [SerializeField] private Button resetButton;
        [SerializeField] private Button saveButton;
        [SerializeField] private Button loadButton;
        [SerializeField] private Slider timeScaleSlider;
        [SerializeField] private Text timeScaleText;
        
        [Header("统计信息UI")]
        [SerializeField] private Text totalAgentsText;
        [SerializeField] private Text totalEventsText;
        [SerializeField] private Text totalMemoriesText;
        [SerializeField] private Text environmentStatsText;
        
        // 内部状态
        private EnvironmentManager environmentManager;
        private List<AgentController> monitoredAgents;
        private AgentController selectedAgent;
        private DateTime lastUIUpdate;
        private float uiUpdateInterval = 1f;
        private bool isPaused = false;
        
        private void Awake()
        {
            InitializeUI();
        }
        
        private void Start()
        {
            SetupUIConnections();
            StartUIUpdates();
        }
        
        private void Update()
        {
            UpdateUI();
        }
        
        /// <summary>
        /// 初始化UI
        /// </summary>
        private void InitializeUI()
        {
            try
            {
                // 确保Canvas存在
                if (mainCanvas == null)
                {
                    mainCanvas = GetComponentInParent<Canvas>();
                }
                
                // 初始化数据结构
                monitoredAgents = new List<AgentController>();
                lastUIUpdate = DateTime.Now;
                
                // 设置初始状态
                if (detailPanel != null)
                {
                    detailPanel.SetActive(false);
                }
                
                Debug.Log("[AgentMonitorUI] UI initialized successfully");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentMonitorUI] Error initializing UI: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 设置UI连接
        /// </summary>
        private void SetupUIConnections()
        {
            try
            {
                // 找到环境管理器
                environmentManager = FindObjectOfType<EnvironmentManager>();
                if (environmentManager != null)
                {
                    environmentManager.OnAgentRegistered += OnAgentRegistered;
                    environmentManager.OnAgentUnregistered += OnAgentUnregistered;
                }
                
                // 设置按钮事件
                if (pauseButton != null)
                {
                    pauseButton.onClick.AddListener(TogglePause);
                }
                
                if (resetButton != null)
                {
                    resetButton.onClick.AddListener(ResetAllAgents);
                }
                
                if (saveButton != null)
                {
                    saveButton.onClick.AddListener(SaveAgentData);
                }
                
                if (loadButton != null)
                {
                    loadButton.onClick.AddListener(LoadAgentData);
                }
                
                if (timeScaleSlider != null)
                {
                    timeScaleSlider.onValueChanged.AddListener(OnTimeScaleChanged);
                    timeScaleSlider.value = Time.timeScale;
                }
                
                // 扫描现有智能体
                ScanExistingAgents();
                
                Debug.Log("[AgentMonitorUI] UI connections setup complete");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentMonitorUI] Error setting up UI connections: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 扫描现有智能体
        /// </summary>
        private void ScanExistingAgents()
        {
            var existingAgents = FindObjectsOfType<AgentController>();
            foreach (var agent in existingAgents)
            {
                OnAgentRegistered(agent);
            }
        }
        
        /// <summary>
        /// 开始UI更新
        /// </summary>
        private void StartUIUpdates()
        {
            InvokeRepeating(nameof(PerformUIUpdate), 0f, uiUpdateInterval);
        }
        
        /// <summary>
        /// 更新UI
        /// </summary>
        private void UpdateUI()
        {
            // 实时更新选中智能体的详细信息
            if (selectedAgent != null && detailPanel != null && detailPanel.activeInHierarchy)
            {
                UpdateAgentDetails();
            }
        }
        
        /// <summary>
        /// 执行UI更新
        /// </summary>
        private void PerformUIUpdate()
        {
            try
            {
                lastUIUpdate = DateTime.Now;
                
                // 更新统计信息
                UpdateStatistics();
                
                // 更新智能体列表
                UpdateAgentList();
                
                // 更新环境信息
                UpdateEnvironmentInfo();
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentMonitorUI] Error in UI update: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新统计信息
        /// </summary>
        private void UpdateStatistics()
        {
            if (totalAgentsText != null)
            {
                totalAgentsText.text = $"Agents: {monitoredAgents.Count}";
            }
            
            // 计算总事件数
            int totalEvents = 0;
            int totalMemories = 0;
            
            foreach (var agent in monitoredAgents)
            {
                if (agent != null)
                {
                    var memorySystem = agent.GetComponent<MemorySystem>();
                    if (memorySystem != null)
                    {
                        totalMemories += memorySystem.AssociativeMemory.GetMemoryCount();
                    }
                }
            }
            
            if (totalEventsText != null)
            {
                totalEventsText.text = $"Events: {totalEvents}";
            }
            
            if (totalMemoriesText != null)
            {
                totalMemoriesText.text = $"Memories: {totalMemories}";
            }
        }
        
        /// <summary>
        /// 更新智能体列表
        /// </summary>
        private void UpdateAgentList()
        {
            if (agentListContent == null) return;
            
            // 清理无效智能体
            monitoredAgents.RemoveAll(agent => agent == null);
            
            // 更新现有项目或创建新项目
            for (int i = 0; i < monitoredAgents.Count; i++)
            {
                var agent = monitoredAgents[i];
                
                // 检查是否已有对应的UI项目
                Transform existingItem = null;
                if (i < agentListContent.childCount)
                {
                    existingItem = agentListContent.GetChild(i);
                }
                
                if (existingItem == null && agentItemPrefab != null)
                {
                    // 创建新的智能体项目
                    var newItem = Instantiate(agentItemPrefab, agentListContent);
                    SetupAgentItem(newItem, agent);
                }
                else if (existingItem != null)
                {
                    // 更新现有项目
                    UpdateAgentItem(existingItem.gameObject, agent);
                }
            }
            
            // 移除多余的UI项目
            while (agentListContent.childCount > monitoredAgents.Count)
            {
                DestroyImmediate(agentListContent.GetChild(agentListContent.childCount - 1).gameObject);
            }
        }
        
        /// <summary>
        /// 设置智能体项目
        /// </summary>
        private void SetupAgentItem(GameObject item, AgentController agent)
        {
            var button = item.GetComponent<Button>();
            if (button != null)
            {
                button.onClick.RemoveAllListeners();
                button.onClick.AddListener(() => SelectAgent(agent));
            }
            
            UpdateAgentItem(item, agent);
        }
        
        /// <summary>
        /// 更新智能体项目
        /// </summary>
        private void UpdateAgentItem(GameObject item, AgentController agent)
        {
            if (agent == null) return;
            
            var agentState = agent.GetAgentState();
            var nameText = item.transform.Find("NameText")?.GetComponent<Text>();
            var statusText = item.transform.Find("StatusText")?.GetComponent<Text>();
            var statusImage = item.transform.Find("StatusImage")?.GetComponent<Image>();
            
            if (nameText != null)
            {
                nameText.text = agentState?.agentName ?? agent.name;
            }
            
            if (statusText != null)
            {
                statusText.text = agentState?.currentAction ?? "Unknown";
            }
            
            if (statusImage != null)
            {
                // 根据智能体状态设置颜色
                if (agentState != null)
                {
                    statusImage.color = GetStatusColor(agentState.mood, agentState.energy);
                }
            }
        }
        
        /// <summary>
        /// 获取状态颜色
        /// </summary>
        private Color GetStatusColor(string mood, float energy)
        {
            // 基于心情和能量返回颜色
            if (energy < 0.3f)
            {
                return Color.red; // 低能量
            }
            else if (mood == "excited")
            {
                return Color.green; // 兴奋
            }
            else if (mood == "content")
            {
                return Color.blue; // 满足
            }
            else if (mood == "tired")
            {
                return Color.yellow; // 疲惫
            }
            else
            {
                return Color.gray; // 中性
            }
        }
        
        /// <summary>
        /// 选择智能体
        /// </summary>
        private void SelectAgent(AgentController agent)
        {
            selectedAgent = agent;
            
            if (detailPanel != null)
            {
                detailPanel.SetActive(true);
            }
            
            UpdateAgentDetails();
            
            Debug.Log($"[AgentMonitorUI] Selected agent: {agent.name}");
        }
        
        /// <summary>
        /// 更新智能体详细信息
        /// </summary>
        private void UpdateAgentDetails()
        {
            if (selectedAgent == null) return;
            
            var agentState = selectedAgent.GetAgentState();
            var scratchMemory = selectedAgent.GetScratchMemory();
            
            // 更新基础信息
            if (agentNameText != null)
            {
                agentNameText.text = agentState?.agentName ?? selectedAgent.name;
            }
            
            if (agentStateText != null)
            {
                agentStateText.text = selectedAgent.GetAgentStats();
            }
            
            if (currentActionText != null)
            {
                currentActionText.text = agentState?.currentAction ?? "Unknown";
            }
            
            if (locationText != null)
            {
                locationText.text = agentState?.currentLocationName ?? "Unknown";
            }
            
            if (moodText != null)
            {
                moodText.text = agentState?.mood ?? "Unknown";
            }
            
            if (energyText != null)
            {
                energyText.text = $"{(agentState?.energy ?? 0):F2}";
            }
            
            // 更新记忆信息
            var memorySystem = selectedAgent.GetComponent<MemorySystem>();
            if (memorySystem != null && memoryCountText != null)
            {
                memoryCountText.text = $"Memories: {memorySystem.AssociativeMemory.GetMemoryCount()}";
            }
            
            // 更新记忆列表
            UpdateMemoryList();
        }
        
        /// <summary>
        /// 更新记忆列表
        /// </summary>
        private void UpdateMemoryList()
        {
            if (selectedAgent == null || memoryContent == null) return;
            
            var memorySystem = selectedAgent.GetComponent<MemorySystem>();
            if (memorySystem == null) return;
            
            // 清空现有内容
            foreach (Transform child in memoryContent)
            {
                Destroy(child.gameObject);
            }
            
            // 获取最近的记忆
            var recentMemories = memorySystem.AssociativeMemory.GetRecentMemories(TimeSpan.FromHours(1), 10);
            
            foreach (var memory in recentMemories)
            {
                if (memoryItemPrefab != null)
                {
                    var memoryItem = Instantiate(memoryItemPrefab, memoryContent);
                    SetupMemoryItem(memoryItem, memory);
                }
            }
        }
        
        /// <summary>
        /// 设置记忆项目
        /// </summary>
        private void SetupMemoryItem(GameObject item, MemoryNode memory)
        {
            var descriptionText = item.transform.Find("DescriptionText")?.GetComponent<Text>();
            var timeText = item.transform.Find("TimeText")?.GetComponent<Text>();
            var importanceText = item.transform.Find("ImportanceText")?.GetComponent<Text>();
            
            if (descriptionText != null)
            {
                descriptionText.text = memory.description;
            }
            
            if (timeText != null)
            {
                timeText.text = memory.createdTime.ToString("HH:mm:ss");
            }
            
            if (importanceText != null)
            {
                importanceText.text = $"Imp: {memory.poignancy}";
            }
        }
        
        /// <summary>
        /// 更新环境信息
        /// </summary>
        private void UpdateEnvironmentInfo()
        {
            if (environmentManager != null && environmentStatsText != null)
            {
                environmentStatsText.text = environmentManager.GetEnvironmentStats();
            }
        }
        
        /// <summary>
        /// 智能体注册事件处理
        /// </summary>
        private void OnAgentRegistered(AgentController agent)
        {
            if (!monitoredAgents.Contains(agent))
            {
                monitoredAgents.Add(agent);
                Debug.Log($"[AgentMonitorUI] Monitoring agent: {agent.name}");
            }
        }
        
        /// <summary>
        /// 智能体取消注册事件处理
        /// </summary>
        private void OnAgentUnregistered(AgentController agent)
        {
            monitoredAgents.Remove(agent);
            
            if (selectedAgent == agent)
            {
                selectedAgent = null;
                if (detailPanel != null)
                {
                    detailPanel.SetActive(false);
                }
            }
            
            Debug.Log($"[AgentMonitorUI] Stopped monitoring agent: {agent.name}");
        }
        
        /// <summary>
        /// 切换暂停状态
        /// </summary>
        private void TogglePause()
        {
            isPaused = !isPaused;
            
            foreach (var agent in monitoredAgents)
            {
                if (agent != null)
                {
                    agent.SetCognitiveCyclePaused(isPaused);
                }
            }
            
            if (pauseButton != null)
            {
                var buttonText = pauseButton.GetComponentInChildren<Text>();
                if (buttonText != null)
                {
                    buttonText.text = isPaused ? "Resume" : "Pause";
                }
            }
            
            Debug.Log($"[AgentMonitorUI] Agents {(isPaused ? "paused" : "resumed")}");
        }
        
        /// <summary>
        /// 重置所有智能体
        /// </summary>
        private void ResetAllAgents()
        {
            foreach (var agent in monitoredAgents)
            {
                if (agent != null)
                {
                    agent.ResetAgent();
                }
            }
            
            if (environmentManager != null)
            {
                environmentManager.ResetEnvironment();
            }
            
            Debug.Log("[AgentMonitorUI] All agents and environment reset");
        }
        
        /// <summary>
        /// 保存智能体数据
        /// </summary>
        private void SaveAgentData()
        {
            try
            {
                // 这里应该调用数据持久化系统
                Debug.Log("[AgentMonitorUI] Agent data saved (placeholder)");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentMonitorUI] Error saving agent data: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 加载智能体数据
        /// </summary>
        private void LoadAgentData()
        {
            try
            {
                // 这里应该调用数据持久化系统
                Debug.Log("[AgentMonitorUI] Agent data loaded (placeholder)");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[AgentMonitorUI] Error loading agent data: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 时间缩放改变事件处理
        /// </summary>
        private void OnTimeScaleChanged(float value)
        {
            Time.timeScale = value;
            
            if (timeScaleText != null)
            {
                timeScaleText.text = $"Speed: {value:F1}x";
            }
        }
        
        /// <summary>
        /// 关闭详细面板
        /// </summary>
        public void CloseDetailPanel()
        {
            selectedAgent = null;
            if (detailPanel != null)
            {
                detailPanel.SetActive(false);
            }
        }
        
        /// <summary>
        /// 获取监控的智能体数量
        /// </summary>
        public int GetMonitoredAgentCount()
        {
            return monitoredAgents.Count;
        }
        
        /// <summary>
        /// 设置UI更新间隔
        /// </summary>
        public void SetUIUpdateInterval(float interval)
        {
            uiUpdateInterval = interval;
            CancelInvoke(nameof(PerformUIUpdate));
            InvokeRepeating(nameof(PerformUIUpdate), 0f, uiUpdateInterval);
        }
        
        private void OnDestroy()
        {
            // 清理事件订阅
            if (environmentManager != null)
            {
                environmentManager.OnAgentRegistered -= OnAgentRegistered;
                environmentManager.OnAgentUnregistered -= OnAgentUnregistered;
            }
        }
    }
}